package com.shure.encrypt.plugin;

import com.shure.encrypt.config.StorageEncryptProperties;
import com.shure.encrypt.encrypt.EncryptService;
import com.shure.encrypt.utils.EncryptDecryptConfigUtils;
import com.shure.encrypt.utils.EncryptDecryptUtils;
import lombok.AllArgsConstructor;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;

import java.sql.Statement;
import java.util.List;
import java.util.Objects;

@Intercepts({
        @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})
})
@AllArgsConstructor
public class ResultInterceptor implements Interceptor {

    private final StorageEncryptProperties storageEncryptProperties;
    private final EncryptService encryptService;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (!storageEncryptProperties.isEnable()) {
            return invocation.proceed();
        }

        Object result = invocation.proceed();
        if (Objects.isNull(result)) {
            return null;
        }
        if (result instanceof List) {
            // 注解字段解密
            EncryptDecryptUtils.fieldListDecrypt(result, encryptService);
            // 配置字段解密
            EncryptDecryptConfigUtils.fieldListDecrypt(result, storageEncryptProperties.getEntities(), encryptService);
        } else if (!EncryptDecryptUtils.notToDecrypt(result)) {
            // 判断有加解密注解
            EncryptDecryptUtils.decrypt(EncryptDecryptUtils.getFields(result.getClass()), result, encryptService);
        } else {
            EncryptDecryptUtils.decrypt(EncryptDecryptConfigUtils.getFields(result.getClass(), storageEncryptProperties.getEntities()), result, encryptService);
        }
        return result;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
}
